from google.appengine.ext import webapp, db
from google.appengine.api.datastore_errors import BadKeyError
from app.models import Job
from app.models.fieldsets import FieldSet, DEFAULT_PRIMARY_FIELDSET
from app.helpers.views import renders_template
from app.helpers.queries import Query
from app.helpers.access import requires_permission

class QueryAll(webapp.RequestHandler):
  """ Redirects to create a new checkout """
  @requires_permission('download')
  def post(self):
    include_fieldset_keys = self.request.get_all('fieldset')
    include_fieldset_keys = [db.Key(key) for key in include_fieldset_keys]
    if not DEFAULT_PRIMARY_FIELDSET.key() in include_fieldset_keys:
      include_fieldset_keys.insert(0, DEFAULT_PRIMARY_FIELDSET.key())
    filter_fieldset_keys = include_fieldset_keys
    tags = self.request.get_all('filter')
    
    job = Job(handler='query_all',
      dataset_key = self.dataset.key(),
      user = self.user,
      include_fieldset_keys = include_fieldset_keys,
      filter_fieldset_keys = filter_fieldset_keys or None,
      tags = tags or None)
    job.put()
    
    self.redirect(job.redirect_link())
